package my.sample.quartz;

import static org.quartz.CronScheduleBuilder.cronSchedule;
import static org.quartz.JobBuilder.newJob;
import static org.quartz.TriggerBuilder.newTrigger;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Date;

import org.quartz.CronTrigger;
import org.quartz.Job;
import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.impl.StdSchedulerFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class JobPooling implements Job {

	/**
	 * @param args
	 * @throws SchedulerException 
	 */
	public static void main(String[] args) throws SchedulerException {
		// TODO Auto-generated method stub
		
		Logger log = LoggerFactory.getLogger(JobPooling.class);
		
		SchedulerFactory fact = new StdSchedulerFactory();
		Scheduler scheduler = fact.getScheduler();
		scheduler.start();
		
		// job
		JobDetail job = newJob(JobPooling.class).withIdentity("myFirstJob", "myGroup").build();
		JobDetail job1 = newJob(JobPooling.class).withIdentity("mySecondJob", "myGroup").build();
		// trigger
        CronTrigger trigger = newTrigger().withIdentity("firstTrigger", "triggerGroup").withSchedule(cronSchedule("0/5 * * * * ?")).build();
        CronTrigger trigger1 = newTrigger().withIdentity("secondTrigger", "triggerGroup").withSchedule(cronSchedule("0/5 * * * * ?")).build();
        
		scheduler.scheduleJob(job, trigger);
		scheduler.scheduleJob(job1, trigger1);
		log.info("sch started");
	}

	@Override
	public void execute(JobExecutionContext context) throws JobExecutionException {
		try {
			
			String fileName = context.getJobDetail().getKey().getName();
			File file = new File(fileName + ".txt");

			// if file doesnt exists, then create it
			if (!file.exists()) {
				file.createNewFile();
			}

			// true = append file
			FileWriter fileWritter = new FileWriter(file.getName(), true);
			BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
			bufferWritter.write(new Date().toString() + "\n");
			bufferWritter.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

}
